var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
let cors = require('cors');
const WebSocket = require('ws');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var lqRouter = require('./routes/lq');
var zlpsRouter = require('./routes/zlp');
var zgnRouter = require('./routes/zgn');
var cxsRouter = require('./routes/cxs');
var lzRouter = require('./routes/lz');
var lzhRouter = require('./routes/lzh');
var messagesRouter = require('./routes/messages');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use('/public',express.static(path.join(__dirname, 'public')));
app.use(cors());

// Add a route handler for WebSocket connection validation
app.get('/', (req, res) => {
  const userId = req.query.userId;
  if (!userId) {
    res.status(400).json({ error: 'Missing userId parameter' });
    return;
  }
  res.status(200).json({ status: 'ok' });
});

app.use('/', indexRouter);  // Changed from '/' to '/api'
app.use('/users', usersRouter);
app.use('/lq', lqRouter);
app.use('/zlp', zlpsRouter);
app.use('/zgn', zgnRouter);
app.use('/', cxsRouter);  // Changed from '/' to '/api/cxs'
app.use('/lz', lzRouter);
app.use('/lzh', lzhRouter);
app.use('/api/messages', messagesRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

// Export the WebSocket setup function
function setupWebSocket(server) {
  const wss = new WebSocket.Server({ server });
  const clients = new Map();

  wss.on('connection', (ws, req) => {
    const userId = new URL(req.url, 'http://localhost').searchParams.get('userId');
    if (userId) {
      clients.set(userId, ws);
    }

    ws.on('message', async (message) => {
      const data = JSON.parse(message);
      if (data.type === 'chat' && data.to) {
        // 转发消息给目标用户
        const targetWs = clients.get(data.to);
        if (targetWs) {
          targetWs.send(JSON.stringify(data));
        }
      }
    });

    ws.on('close', () => {
      if (userId) {
        clients.delete(userId);
      }
    });
  });

  return wss;
}

module.exports = { app, setupWebSocket };
